package home

import (
	"adai.design/homeserver/home/data"
	"adai.design/homeserver/members"
	"encoding/json"
)

const (
	TypeAccessoryInformation = "1"	// 配件基本属性
	TypeAccessoryBridge 	 = "2"	// 桥接服务
	TypeAccessoryDFU		 = "3"	// 固件升级

	TypeContactSensor     = "11" // 接触传感器: 门磁
	TypeHTSensor    	  = "12" // 湿度计
	TypeLightSensor       = "13" // 光线传感器
	TypeOutlet            = "14" // 插座
	TypeSwitch            = "15" // 开关
	TypeAirConditioner    = "16" // 空调
	TypeClock			  = "17" // 闹钟
)

type Service struct {
	AId    	string 		`json:"aid" bson:"aid"`
	SId    	int    		`json:"sid" bson:"sid"`
	Name   	string 		`json:"name" bson:"name"`
	Type   	string 		`json:"type" bson:"type"`
	Icon   	string 		`json:"icon" bson:"icon"`
	Room   	string 		`json:"room" bson:"room"`
	Notify 	bool   		`json:"notify" bson:"notify"`		// 状态改变是否需要推送消息
}

const (
	ContactSensorStateContactDetected  = 0
	ContactSensorStateContactNotDetected  = 1
)

func (s *Service) handleContactSensorNotify(h *Home, char *data.Characteristic) {
	title := h.Name
	subtitle := h.getRoomNameById(s.Room) + "的" + s.Name + "被"
	//log.Debug("contact sensor value(%v)", char.Value)
	if char.Value == float64(ContactSensorStateContactNotDetected) {
		subtitle += "关闭了"
	} else {
		subtitle += "打开了"
	}

	push := &members.APNSAlert{
		Title: title,
		Body: subtitle,
	}
	h.pushNotifyToMember(push)
}

type ServiceManager struct {
	services []*Service
}

func (s *ServiceManager) getService(char *data.Characteristic) *Service {
	for _, c := range s.services {
		if c.AId == char.AId && c.SId == char.SId {
			return c
		}
	}
	return nil
}

func (s *ServiceManager) CheckNotify(h *Home, char *data.Characteristic) {
	for _, c := range s.services {
		if c.AId == char.AId && c.SId == char.SId && c.Notify {
			switch c.Type {
			// 暂时只处理门磁的推送信息
			case TypeContactSensor:
				c.handleContactSensorNotify(h, char)
			}
		}
	}
}

func (s *ServiceManager) Handle(h *Home, pkg *members.MessagePkg) error {
	msg := pkg.Msg
	if msg.Method == members.MsgMethodGet {
		buf, _ := json.Marshal(s.services)
		ack := &members.MessagePkg{
			Type: pkg.Type,
			Ctx: pkg.Ctx,
			Msg: &members.Message{
				Path: msg.Path,
				Method: msg.Method,
				State: "ok",
				Home: h.Id,
				Data: buf,
			},
		}
		h.replyMemberResult(ack)
	}
	return nil
}





